<?php
/**
 * 新浪微博第三方登录驱动
 */
namespace mcOAuth\Driver;
class weibo extends \mcOAuth\OAuth{
    protected $API_URL = 'https://api.weibo.com/';

    /**
     * 生成获取AuthorizeCode地址
     * @return url
     */
    protected function buildAuthorizeCodeURL(){
        $params=array(
            'response_type' =>'code',
            'client_id'     =>$this->config['APP_ID'],
            'redirect_uri'  =>$this->config['callback'],
            'scope'         =>$this->config['scope'],
            'display'       =>$this->config['display'],
            'state'         =>$this->AuthorizeState,
        );
        $url=$this->buildAPI('oauth2/authorize',$params);
        return $url;
    }

    /**
     * 获取AccessToken
     */
    protected function doGetAccessToken(){
        $params=array(
            'grant_type'    =>'authorization_code',
            'client_id'     =>$this->config['APP_ID'],
            'client_secret' =>$this->config['APP_KEY'],
            'code'          =>$this->AuthorizeCode,
            'redirect_uri'  =>$this->config['callback'],
        );
        $result=$this->requestAPI('oauth2/access_token?'.http_build_query($params),array(),'POST');
        $data=json_decode($result,true);
        if(!isset($data['error'])){
            return $this->setAccessTokenAttr($data);
        }else{
            exception($result);
        }
    }

    /**
     * 格式化获取的AccessToken数据
     */
    protected function setAccessTokenAttr($data){
        $this->AccessToken=$data['access_token'];
        $this->OpenID=$data['uid'];
        $params = array(
            'access_token'  => $data['access_token'],
            'expires_in'    => $data['expires_in'],
            'refresh_token' => '',
            'openid'        => $data['uid'],
            'create_at'     => time()
        );
        return $params;
    }

    /**
     * 获取OpenID
     */
    protected function doGetOpenID(){
        return $this->OpenID;
    }

    /**
     * 格式化获取的OpenID数据
     */
    protected function setOpenIDAttr($data){
    }

    /**
     * 获取用户信息
     */
    protected function doGetUserInfo(){
        $params=array(
            'access_token' =>$this->AccessToken,
            'uid'          =>$this->OpenID
        );
        $result=$this->requestAPI('2/users/show.json',$params);
        if(!empty($result)){
            $data=json_decode($result,true);
            $data=$this->setUserInfoAttr($data);
            return $data;
        }else{
            exception('获取UserInfo失败，请重试！');
        }
    }

    /**
     * 格式化获取的用户信息数据
     */
    protected function setUserInfoAttr($data){
        $params = array(
            'openid'   => $this->OpenID,
            'channel'  => $this->config['channel'],
            'nickname' => $data['screen_name'],
            'gender'   => $data['gender'],
            'avatar'   => $data['avatar_hd']
        );
        return $params;
    }
}
